package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.etity.Category;
import com.example.etity.Employee;
import com.example.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping()
    public R<String> addCategory(@RequestBody Category category){
        boolean save = categoryService.save(category);
        log.info("category:{}",category);
        if (save) return R.success("新增分类成功");
        return R.error("新增分类失败");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){
        log.info("page={}，pageSize={}",page,pageSize);

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
//        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Category::getUpdateTime);
        //执行查询
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 根据给定id删除分类
     * @param id
     * @return
     */
    @DeleteMapping()
    public R<String> deleteById(Long id){
//        boolean b = categoryService.removeById(id);
//        if (b) return R.success("删除分类成功");
        categoryService.remove(id);
        return R.success("删除分类成功");
    }

    @PutMapping()
    public R<String> update(@RequestBody Category category){

        boolean b = categoryService.updateById(category);
        return R.success("修改分类成功");
    }

    @GetMapping("/list")
    public R<List<Category>> listCategory(Category category){
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }
}
